import os
import shutil
import yaml
import mariadb

# 加载配置文件
def load_config():
    # 获取当前目录的 config 文件夹路径
    config_dir = os.path.join(os.path.dirname(__file__), 'config')
    default_config_path = os.path.join(config_dir, 'config_default.yaml')
    user_config_path = os.path.join(config_dir, 'config.yaml')

    # 打印调试信息
    print(f"默认配置文件路径: {default_config_path}")
    print(f"用户配置文件路径: {user_config_path}")

    # 如果用户配置文件不存在，则复制默认配置文件
    if not os.path.exists(user_config_path):
        print(f"在 {user_config_path} 创建用户配置文件")
        try:
            shutil.copyfile(default_config_path, user_config_path)
            print("用户配置文件创建成功。")
        except Exception as e:
            print(f"创建用户配置文件失败: {e}")
            raise
    else:
        print("用户配置文件已存在。")

    # 加载配置文件
    try:
        with open(user_config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        print("用户配置文件加载成功。")
    except Exception as e:
        print(f"加载用户配置文件失败: {e}")
        raise

    return config

# 执行 SQL 文件
def execute_sql_file(cursor, sql_file):
    with open(sql_file, 'r', encoding='utf-8') as file:
        sql_commands = file.read().split(';')
        for command in sql_commands:
            if command.strip():
                try:
                    cursor.execute(command)
                except mariadb.Error as e:
                    print(f"执行命令时出错: {command}\n错误: {e}")

def main():
    # 加载配置
    config = load_config()
    db_config = config['database']

    # SQL 文件路径
    sql_file_path = os.path.join(os.path.dirname(__file__), 'sql', 'sql执行语句')

    conn = None
    try:
        # 连接到 MariaDB 服务器（不指定数据库）
        conn = mariadb.connect(
            host=db_config['host'],
            port=db_config['port'],
            user=db_config['user'],
            password=db_config['password']
        )
        cursor = conn.cursor()
        print("成功连接到 MariaDB 服务器。")

        # 创建数据库（如果不存在）
        cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_config['dbname']} CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;")
        print(f"数据库 {db_config['dbname']} 创建成功或已存在。")

        # 连接到指定数据库
        conn.select_db(db_config['dbname'])

        # 执行 SQL 文件
        execute_sql_file(cursor, sql_file_path)
        conn.commit()
        print("SQL 文件执行成功。")

    except mariadb.Error as e:
        print(f"连接到 MariaDB 时出错: {e}")
    finally:
        if conn:
            conn.close()
            print("数据库连接已关闭。")

if __name__ == "__main__":
    main()
